package cn.com.se.sharepictrue.utils;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.URLS;
import cz.msebera.android.httpclient.Header;

/**
 * 访问网络API
 * Created by KIDNG on 2015/11/13.
 */
public class BusinessUtils {
    private static final String PASSWORD_KEY = "password";
    private static String PHONE_KEY="userPhone";
    private static final int DEFAULT_TIME_OUT = 6000;

    private static AsyncHttpClient client = new AsyncHttpClient();

    static {
        client.setTimeout(DEFAULT_TIME_OUT);
    }
    private BusinessUtils(){}

    public static void setPersistentCookieStore(Context context) {
        context = context.getApplicationContext();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
        client.setCookieStore(myCookieStore);
    }
    public interface RegisterCallBack{
        void start();
        void success(String msg);
        void fail(String msg);
        void error(String msg);
    }
    public static AsyncHttpClient register(String phone,String password, final RegisterCallBack callBack){
        RequestParams params = new RequestParams();
        params.put(PHONE_KEY,phone);
        params.put(PASSWORD_KEY, password);
        client.post(URLS.register,params, new BaseJsonHttpResponseHandler<NetworkResponse>() {
            @Override
            public void onStart() {
                super.onStart();
                callBack.start();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, NetworkResponse response) {
                if(response.isStatus()){
                    callBack.success(response.getError());
                }else {
                    callBack.fail(response.getError());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, NetworkResponse errorResponse) {
                callBack.error("");
            }

            @Override
            protected NetworkResponse parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                if(isFailure)
                    return null;
                else
                    return new Gson().fromJson(rawJsonData,new TypeToken<NetworkResponse>(){}.getType());
            }
        });
        return client;
    }

}
